#ifndef U2VertexIndexData_H__
#define U2VertexIndexData_H__


#include "U2PreRequest.h"
#include "U2MemoryAllocatorConfig.h"
#include "U2SharedPtr.h"
#include "U2HardwareVertexBuffer.h"
#include "U2HardwareIndexBuffer.h"


U2EG_NAMESPACE_BEGIN



/// Define a list of usage flags
typedef std::vector<U2HardwareBuffer::Usage> BufferUsageList;


/** Summary class collecting together vertex source information. */
class _U2Share U2VertexData : public VertexDataAlloc
{
private:
    /// Protected copy constructor, to prevent misuse
    U2VertexData(const U2VertexData& rhs); /* do nothing, should not use */
    /// Protected operator=, to prevent misuse
    U2VertexData& operator=(const U2VertexData& rhs); /* do not use */

	U2HardwareBufferManagerBase* mMgr;
public:
	/** Constructor.
	@note 
		This constructor creates the U2VertexDeclaration and U2VertexBufferBinding
		automatically, and arranges for their deletion afterwards.
	@param mgr Optional HardwareBufferManager from which to create resources
	*/
    U2VertexData(U2HardwareBufferManagerBase* mgr = 0);
	/** Constructor.
	@note 
	This constructor receives the U2VertexDeclaration and U2VertexBufferBinding
	from the caller, and as such does not arrange for their deletion afterwards, 
	the caller remains responsible for that.
	@param dcl The U2VertexDeclaration to use
	@param bind The U2VertexBufferBinding to use
	*/
	U2VertexData(U2VertexDeclaration* dcl, U2VertexBufferBinding* bind);
    ~U2VertexData();

	/** Declaration of the vertex to be used in this operation. 
	@remarks Note that this is created for you on construction.
	*/
	U2VertexDeclaration* vertexDeclaration;
	/** The vertex buffer bindings to be used. 
	@remarks Note that this is created for you on construction.
	*/
	U2VertexBufferBinding* vertexBufferBinding;
	/// Whether this class should delete the declaration and binding
	bool mDeleteDclBinding;
	/// The base vertex index to start from
	size_t vertexStart;
	/// The number of vertices used in this operation
	size_t vertexCount;

	
	/** Clones this vertex data, potentially including replicating any vertex buffers.
	@param copyData Whether to create new vertex buffers too or just reference the existing ones
	@param mgr If supplied, the buffer manager through which copies should be made
	@remarks The caller is expected to delete the returned pointer when ready
	*/
	U2VertexData* clone(bool copyData = true, U2HardwareBufferManagerBase* mgr = 0) const;


	/** Reorganises the data in the vertex buffers according to the 
		new vertex declaration passed in. Note that new vertex buffers
		are created and written to, so if the buffers being referenced 
		by this vertex data object are also used by others, then the 
		original buffers will not be damaged by this operation.
		Once this operation has completed, the new declaration 
		passed in will overwrite the current one.
	@param newDeclaration The vertex declaration which will be used
		for the reorganised buffer state. Note that the new declaration
		must not include any elements which do not already exist in the 
		current declaration; you can drop elements by 
		excluding them from the declaration if you wish, however.
	@param bufferUsages Vector of usage flags which indicate the usage options
		for each new vertex buffer created. The indexes of the entries must correspond
		to the buffer binding values referenced in the declaration.
	@param mgr Optional pointer to the manager to use to create new declarations
		and buffers etc. If not supplied, the HardwareBufferManager singleton will be used
	*/
	void reorganiseBuffers(U2VertexDeclaration* newDeclaration, const BufferUsageList& bufferUsage, 
		U2HardwareBufferManagerBase* mgr = 0);

	/** Reorganises the data in the vertex buffers according to the 
		new vertex declaration passed in. Note that new vertex buffers
		are created and written to, so if the buffers being referenced 
		by this vertex data object are also used by others, then the 
		original buffers will not be damaged by this operation.
		Once this operation has completed, the new declaration 
		passed in will overwrite the current one.
        This version of the method derives the buffer usages from the existing
        buffers, by using the 'most flexible' usage from the equivalent sources.
	@param newDeclaration The vertex declaration which will be used
		for the reorganised buffer state. Note that the new delcaration
		must not include any elements which do not already exist in the 
		current declaration; you can drop elements by 
		excluding them from the declaration if you wish, however.
	@param mgr Optional pointer to the manager to use to create new declarations
		and buffers etc. If not supplied, the HardwareBufferManager singleton will be used
	*/
	void reorganiseBuffers(U2VertexDeclaration* newDeclaration, U2HardwareBufferManagerBase* mgr = 0);

    /** Remove any gaps in the vertex buffer bindings.
    @remarks
        This is useful if you've removed elements and buffers from this vertex
        data and want to remove any gaps in the vertex buffer bindings. This
        method is mainly useful when reorganising vertex data manually.
    @note
        This will cause binding index of the elements in the vertex declaration
        to be altered to new binding index.
    */
    void closeGapsInBindings(void);

    /** Remove all vertex buffers that never used by the vertex declaration.
    @remarks
        This is useful if you've removed elements from the vertex declaration
        and want to unreference buffers that never used any more. This method
        is mainly useful when reorganising vertex data manually.
    @note
        This also remove any gaps in the vertex buffer bindings.
    */
    void removeUnusedBuffers(void);

	/** Convert all packed colour values (VET_COLOUR_*) in buffers used to
		another type.
	@param srcType The source colour type to assume if the ambiguous VET_COLOUR
		is encountered.
	@param destType The destination colour type, must be VET_COLOUR_ABGR or
		VET_COLOUR_ARGB.
	*/
	void convertPackedColour(VertexElementType srcType, VertexElementType destType);

};



/** Summary class collecting together index data source information. */
class _U2Share U2IndexData : public IndexDataAlloc
{
protected:
    /// Protected copy constructor, to prevent misuse
    U2IndexData(const U2IndexData& rhs); /* do nothing, should not use */
    /// Protected operator=, to prevent misuse
    U2IndexData& operator=(const U2IndexData& rhs); /* do not use */
public:
    U2IndexData();
    ~U2IndexData();
	/// pointer to the HardwareIndexBuffer to use, must be specified if useIndexes = true
	U2HardwareIndexBufferSharedPtr indexBuffer;

	/// index in the buffer to start from for this operation
	size_t indexStart;

	/// The number of indexes to use from the buffer
	size_t indexCount;

	/** Clones this index data, potentially including replicating the index buffer.
	@param copyData Whether to create new buffers too or just reference the existing ones
	@param mgr If supplied, the buffer manager through which copies should be made
	@remarks The caller is expected to delete the returned pointer when finished
	*/
	U2IndexData* clone(bool copyData = true, U2HardwareBufferManagerBase* mgr = 0) const;

	/** Re-order the indexes in this index data structure to be more
		vertex cache friendly; that is to re-use the same vertices as close
		together as possible. 
	@remarks
		Can only be used for index data which consists of triangle lists.
		It would in fact be pointless to use it on triangle strips or fans
		in any case.
	*/
	void optimiseVertexCacheTriList(void);

};



/** Vertex cache profiler.
@remarks
	Utility class for evaluating the effectiveness of the use of the vertex
	cache by a given index buffer.
*/
class _U2Share U2VertexCacheProfiler : public BufferAlloc
{
public:
	enum CacheType {
		FIFO, LRU
	};

	U2VertexCacheProfiler(unsigned int cachesize = 16, CacheType cachetype = FIFO )
		: size ( cachesize ), type ( cachetype ), tail (0), buffersize (0), hit (0), miss (0)
	{
		cache = U2_ALLOC_T(u2uint32, size, MEMCATEGORY_GEOMETRY);
	}

	~U2VertexCacheProfiler()
	{
		U2_FREE(cache, MEMCATEGORY_GEOMETRY);
	}

	void profile(const U2HardwareIndexBufferSharedPtr& indexBuffer);
	void reset() { hit = 0; miss = 0; tail = 0; buffersize = 0; }
	void flush() { tail = 0; buffersize = 0; }

	unsigned int getHits() { return hit; }
	unsigned int getMisses() { return miss; }
	unsigned int getSize() { return size; }
private:
	unsigned int size;
	u2uint32 *cache;
	CacheType type;

	unsigned int tail, buffersize;
	unsigned int hit, miss;

	bool inCache(unsigned int index);
};



U2EG_NAMESPACE_END

#endif